package com.zy.net.retrofit;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.zy.net.data.DataRecord;
import com.zy.zlog.ZLog;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

public class RetrofitFactory {
    private static final String TAG = "RetrofitFactory";

    static final Converter.Factory FACTORY = new Converter.Factory() {
        @Override
        public @Nullable
        Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
            ZLog.d(TAG, "responseBodyConverter type:" + type);
            //把返回数据处理成对应数据类型
            if (type == DataRecord.class) return new DataAdapter();
            if (type == String.class) return new StringDataAdapter();
            return null;
        }

        @Override
        public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
            ZLog.d(TAG, "requestBodyConverter type:" + type);
            if (type == DataRecord.class) {
                return new RequestBodyAdapter();
            }
            return null;
        }
    };

    static final class RequestBodyAdapter implements Converter<DataRecord, RequestBody> {
        @Override
        public RequestBody convert(DataRecord blog) throws IOException {
            //把请求数据类处理成符合要求的类型
            StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
            for (StackTraceElement stackTraceElement : stackTrace) {
                System.out.println(stackTraceElement);
            }


            return RequestBody.create(null, blog.toString());
        }
    }


    static final class DataAdapter implements Converter<ResponseBody, DataRecord> {
        @Override
        public DataRecord convert(ResponseBody responseBody) throws IOException {
            String body = responseBody.string();
            // FIXME: 2020/11/16 数据处理
            return new Gson().fromJson(body, DataRecord.class);
        }
    }

    static final class StringDataAdapter implements Converter<ResponseBody, String> {
        @Override
        public String convert(ResponseBody responseBody) throws IOException {
            // FIXME: 2020/11/16 数据处理
            return responseBody.string();
        }
    }
}